#include "CustomListView.h"

#include <QListView>
#include <QKeyEvent>

#include "Constants.h"
#include "commandexecutor.h"
#include <QKeyEvent>
#include <QMessageBox>
#include <QSortFilterProxyModel>




// 配置文件中能运行的字符串所在的列数
#define DATA_OPTION_COLUMN 2
#define DATA_CMD_COLUMN 4

// myglobalfunctions.cpp


// 全局函数定义
QString concatenateStrings(const QString& str1, const QString& str2) {
    return str1 + str2;
}

CustomListView::CustomListView(QWidget *parent) : QListView(parent) {
    this->setFocusPolicy(Qt::FocusPolicy::ClickFocus);
    strListModel = new QStringListModel(this);
    setModel(strListModel);
}

void CustomListView::keyPressEvent(QKeyEvent *event) {
    int key = event->key();
    Qt::KeyboardModifiers modifiers = event->modifiers();
    qDebug() << "Key pressed:" << key ;


    if (event->key() == Qt::Key_Tab) {
        // 获取当前选中项的索引
        QModelIndex currentIndex = this->currentIndex();
        int row = currentIndex.row();

        // 计算下一个项的索引
        int nextRow = (row + 1) % this->model()->rowCount();
        QModelIndex nextIndex = this->model()->index(nextRow, currentIndex.column());

        // 设置下一个项为当前选中项
        this->setCurrentIndex(nextIndex);
    } else if (event->key() == Qt::Key_Space) {
        // 获取当前选中项的索引
        QModelIndex currentIndex = this->currentIndex();
        if (currentIndex.isValid()) {
            // 获取选中项的文本
            QString itemText = this->model()->data(currentIndex).toString();
            // 显示选中项的信息
            QMessageBox::information(this, "Selected Item", "选中行内容: " + itemText);
        }
    } else {
        QString qstr(key);
        emit sig_input(&qstr);
        QListView::keyPressEvent(event);
    }
}

QString CustomListView::getSelectedRowItem() {
    QModelIndex currentIndex = this->currentIndex();
    QString selectedRow = this->model()->data(currentIndex).toString();
    return selectedRow;
}

QString CustomListView::getSelectedRowText() {
    QModelIndex currentIndex = this->currentIndex();
    QString itemText = this->model()->data(currentIndex).toString();
    if(!itemText.isEmpty()){
        QStringList qstrList = itemText.split("|");
        QString qStr = qstrList.at(DATA_CMD_COLUMN);
        return qStr;
    }else{
        return "";
    }
}
void CustomListView::itemMovedSlot(int value,QString text) {
    // 处理信号
    qDebug() << "CustomListView--->itemMovedSlot槽函数处理信号"<<value<<",text="<<text;

    QModelIndex currentIndex = this->currentIndex();
    int row = currentIndex.row();


    // 计算下一个项的索引
    int nextRow = (row + 1) % this->model()->rowCount();
    QModelIndex nextIndex = this->model()->index(nextRow, 0);


    // 设置下一个项为当前选中项
    this->setCurrentIndex(nextIndex);

    // 假设listView是QListView对象，row是要选中项的行号，column是要选中项的列号
    // this->setCurrentIndex(this->model()->index(2, 0));
}

void CustomListView::itemMovedPrevSlot(int value,QString text) {
    // 处理信号
    qDebug() << "CustomListView--->itemMovedPrevSlot槽函数处理信号"<<value<<",text="<<text;

    QModelIndex currentIndex = this->currentIndex();
    int row = currentIndex.row();


    // 计算下一个项的索引
    int nextRow = (row - 1) % this->model()->rowCount();
    if(nextRow == -1){
        nextRow = this->model()->rowCount() - 1;//跳到最后一行
    }
    QModelIndex nextIndex = this->model()->index(nextRow, 0);


    // 设置下一个项为当前选中项
    this->setCurrentIndex(nextIndex);
}

void CustomListView::filterDataSlot(const QStringList &initTextList,const QString &filterText) {
    // QStringList filteredList = this->originalData.filter(filterText, Qt::CaseInsensitive);
    // qDebug() << "CustomListView--->filterDataSlot-"<<filterText ;
    // 获取模型
    // listViewModel = qobject_cast<QStandardItemModel*>(this->model());
    strListModel = qobject_cast<QStringListModel*>(this->model());
    //QStringList initTextList = strListModel->stringList();
    QString searchStr = filterText;
    /*方式一：更新model方式
     * 1、遍历字符串列表，判断单个字符串中是否含有搜索框字符，存入新的QStringList；
     * 2、更新model，在界面的listView中重新显示； */
    QStringList newModelStr;
    /*if(!searchStr.isEmpty()){
        foreach (QString tmpStr, initTextList) {
            QStringList tempList  = tmpStr.split("|");
            QString tmpStr1 = tempList.at(DATA_OPTION_COLUMN);
            if (tmpStr1.trimmed().contains(searchStr, Qt::CaseInsensitive)) {
                newModelStr.append(tmpStr);
            } else {
                continue;
            }
        }
        qDebug() << "筛选结果："<< newModelStr;
        // 解析并排序数据
        QList<QPair<int, QString>> sortedData = this->parseAndSortData(newModelStr);
        // 添加序号列
        QStringList indexedData = this->addIndexColumn(sortedData);

        // 设置初始数据
        // this->setData(indexedData);
        // QStringListModel model(indexedData);
        // this->setModel(&model);
        this->setData(indexedData);
        this->setModel(strListModel);
        // strListModel->setStringList(newModelStr);
    }else{
         // 解析并排序数据
         QList<QPair<int, QString>> sortedData = this->parseAndSortData(newModelStr);
         // 添加序号列
         QStringList indexedData = this->addIndexColumn(sortedData);
         this->setData(indexedData);
         this->setModel(strListModel);
    }*/

    foreach (QString tmpStr, initTextList) {
        QStringList tempList  = tmpStr.split("|");
        QString tmpStr1 = tempList.at(DATA_OPTION_COLUMN);
        if (tmpStr1.trimmed().contains(searchStr, Qt::CaseInsensitive)) {
            newModelStr.append(tmpStr);
        } else {
            continue;
        }
    }
    if(searchStr.isEmpty()){
        newModelStr = initTextList;
    }
    qDebug() << "筛选结果："<< newModelStr;
    // 解析并排序数据
    QList<QPair<int, QString>> sortedData = this->parseAndSortData(newModelStr);
    // 添加序号列
    QStringList indexedData = this->addIndexColumn(sortedData);
    this->setData(indexedData);
    this->setModel(strListModel);

    // 只显示前10条数据
    // this->model()
}


/**
 * QTableView 的 model() 方法返回当前设置的模型
 * @brief CustomTableView::SelectFirstRow
 */
void CustomListView::selectFirstRow()
{
    if (model() && model()->rowCount() > 0) {
        QModelIndex firstIndex = model()->index(0, 0);// 获取代理模型中第一项的索引
        selectionModel()->setCurrentIndex(firstIndex, QItemSelectionModel::Select | QItemSelectionModel::Rows);// 选中firstIndex行
        // this->selectRow(firstIndex.row()); // 选中firstIndex行
    }
}





void CustomListView::runListRow(QString commandParam)
{

    int colNum = Constants::DataColumnNum;
    QStringList cmdList = commandParam.split("|");
    if(cmdList.size() != colNum){
        QMessageBox::information(this, "入参检查", QString("runListRow输入参数不正确: %1").arg(commandParam));
        return;
    }
    // QString cmd = this->getColumnValue(command,DATA_CMD_COLUMN);
    QString command= (cmdList.at(colNum - 1));
    command = command.replace("\"","");
    // 获取QSortFilterProxyModel的选择模型
    QItemSelectionModel *selectionModel = this->selectionModel();

    // 获取当前选中的行
    // QModelIndexList selectedRows = selectionModel->selectedRows();



    CommandExecutor* executor = new CommandExecutor();
    executor->executeCommand(command);
}


QString CustomListView::getColumnValue(const QString& input, int columnIndex) {
    // 使用QStringList来分割字符串
    QStringList columns = input.split("|");

    // 检查列数是否在有效范围内
    if (columnIndex >= 0 && columnIndex < columns.size()) {
        return columns.at(columnIndex);
    } else {
        // 如果列数无效，返回空字符串或抛出异常
        return QString();
    }
}

// 解析输入数据并排序
QList<QPair<int, QString>> CustomListView::parseAndSortData(const QStringList& input) {
    QList<QPair<int, QString>> data;

    for (const QString& line : input) {
        QStringList parts = line.split('|');
        if (parts.size() == 5) {
            QString countStr = parts[0].trimmed().mid(1); // 去掉前缀 'F'
            // qDebug() << "countStr=" <<countStr;
            int count = countStr.toInt();
            data.append(qMakePair(count, line));
        }
    }

    // 按次数从大到小排序
    std::sort(data.begin(), data.end(), [](const QPair<int, QString>& a, const QPair<int, QString>& b) {
        return a.first > b.first;
    });

    return data;
}

// 添加序号列
QStringList CustomListView::addIndexColumn(const QList<QPair<int, QString>>& sortedData) {
    QStringList result;
    int index = 1;

    for (const QPair<int, QString>& item : sortedData) {
        QString line = QString::number(index) + "|" + item.second;
        result.append(line);
        if (index == 10) break; // 只取前十行
        index++;
    }

    return result;
}
